package cn.mall.framework.biz;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;

import cn.mall.framework.biz.bean.BusinessException;
import cn.mall.framework.biz.bean.BusinessRequest;
import cn.mall.framework.biz.bean.BusinessResponse;
import cn.mall.framework.biz.bean.ErrorInfo;
import cn.mall.framework.common.JsonKit;

@Slf4j
@Data
public class WebServiceListener {

	@Resource
	private PublicServiceProcessAsync publicServiceProcessAsync;
	@Resource
	private Map<String, PublicBusinessSystemServiceAsync<BusinessRequest, BusinessResponse>> servicesMap;
	@Resource
	private PublicBusinessProcessSynchronizer businessProcessorSynchronizer;
	@Resource
	private SendCallerMessageService sendCallerMessageService;

	protected String processMessage(String relationId, String srcUUID, String json) {
		try {
			Map<String, String> map = null;
			try {
				map = JsonKit.jsonToMap(json);
			} catch (Exception e1) {
				log.error("[系统内部错误-Json转map异常]");
				return innerError(relationId, srcUUID);
			}
			String msgId = map.get("msgId");
			if (StringUtils.isEmpty(msgId))
				throw new BusinessException("[服务编号必填]");
			return businessProcessorSynchronizer.processRequest(publicServiceProcessAsync, json, relationId, srcUUID);
		} catch (BusinessException e) {
			log.error(e.getErrInfo(), e);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return innerError(relationId, srcUUID);
	}

	protected String innerError(String relationId, String srcUUID) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("errCode", ErrorInfo.INTERNAL_ERROR);
		map.put("errInfo", ErrorInfo.INTERNAL_ERROR_INFO);
		String response = JsonKit.map2json(map);
		if(StringUtils.isNotBlank(relationId) && StringUtils.isNotBlank(srcUUID)){
			sendCallerMessageService.send(relationId, response, srcUUID);
		}
		return response;
	}

}
